#include "blueteeth.h"
#include "stdio.h"
#include "led01.h"
#include "systick.h"
#include "PareJson.h"
TaskHandle_t blueHandler;
extern QueueHandle_t  configMsgHandle;
int checkConfigMsg(int type);
	
void bluetooth_init(){
    usart3_init(9600);
}

void bluetooth_task(void * param){
	 char data[200];
	 while (1) {   	
	 	memset(data, 0, 200);
	 	int index = 0;
			while (1) {
					if(USART_GetFlagStatus(USART3, USART_FLAG_RXNE) != RESET){
						char res = USART_ReceiveData(USART3);
						if(res=='\0'){
							continue;  
						}
						if(res=='\n'){
								data[index] = '\0';
								break;
						}else{
								data[index] = res;
						}
						index++;
			 }
			}
			printf("receive data = %s\r\n",data);
		 
     char *msg=data;
	   //char* msg = "{\"msgType\":1,\"state\":15,\"tempMax\":20,\"tempMin\":20,\"humMax\":20,\"humiMin\":20,\"sunshine\":20,\"smoke\":20}";
			//char* msg="{\"msgType\":1,\"content\":{\"state\":15,\"sunshine\":70}}";
			//char* msg="{\"msgType\":1}";
			/*
				0.把接收到的json通过消息队列去发送
				1.获取到json字符串 --转化为json对象  --cJSON 别人写好的工具
				2.从json对象里面解析数据
				3.存储在eeprom里面 --配置模块-- 单独任务
				4.执行模块从 eeprom中获取数据
			*/
			//获取msg里面的消息类型
			printf("msg=%s\r\n",msg);
			int msgType= parseMsgType(msg);
			printf("msgType=%d\r\n",msgType);
			if(checkConfigMsg(msgType)){
				//投递消息给 配置模块  解析消息 并存储
				if(xQueueSend(configMsgHandle,&msg,portMAX_DELAY)==pdTRUE){
				     printf("send msg success \r\n");	
	      }				
				}else{
				//消息类型不是我们想要的结果
				printf("send msg error \r\n");	
			}

			vTaskDelay(1000);
		}
	
}

void createBluetoothTask(){
    xTaskCreate(
        bluetooth_task,
        "bluetooth_task",
        128,
        NULL,
        2,
        &blueHandler
    );
}

int checkConfigMsg(int type){
	return (type==MSG_TYPE_CONFIG_TH||type==MSG_TYPE_CONFIG_NETWORK)?1:0;
}
